package com.igeek.dao;

import com.igeek.domain.Product;
import com.igeek.utils.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class ProductDao {
    /**
     * 查询热门商品
     */
    public List<Product> findHotProduct() throws SQLException {
        QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
        String sql="select * from product where is_hot=1 limit 0,9";
        return  qr.query(sql,new BeanListHandler<>(Product.class));
    }

    /**
     * 查询最新商品
     * @return
     * @throws SQLException
     */
    public List<Product> findNewProduct() throws SQLException {
        QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
        String sql="select * from product order by pdate desc limit 0,9";
        return  qr.query(sql,new BeanListHandler<>(Product.class));
    }

    /**
     * 查询总条数
     * @param cid
     * @return
     * @throws SQLException
     */
    public int getCountByCid(String cid) throws SQLException {
        QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
        String sql="SELECT count(*) from product where cid=?";
        Object [] params={cid};
        Long count=(Long) qr.query(sql,new ScalarHandler(),params);
        return count.intValue();
    }

    /**
     * 根据分类查询商品数据并分页
     * @param cid
     * @param start
     * @param size
     * @return
     * @throws SQLException
     */
    public List<Product> findProductByCid(String cid,int start,int size) throws SQLException {
        QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
        String sql="select * from product where cid=? limit ?,?";
        Object [] params={cid,start,size};
        return  qr.query(sql,new BeanListHandler<Product>(Product.class),params);
    }

    /**
     * 根据pid查询商品
     * @param pid
     * @return
     * @throws SQLException
     */
    public Product findProductByPid(String pid) throws SQLException {
        QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
        String sql="select * from product where pid=?";
        Object [] params={pid};
        return  qr.query(sql,new BeanHandler<Product>(Product.class),params);
    }
}
